<template>
	<div class="bigScreenBodyDiv">

		<div class="bigScreenBodyDivMain">
			<div id="" style="width: 100%;height: 100%;">
				<div class="home_div" style="position: relative;">
					<div class="map_menu">
						<el-radio-group v-if="over" v-model="layerShowType" size="mini" @change="changeLayerShowType">
							<el-radio-button label="baseDT">默认地图</el-radio-button>
							<el-radio-button label="satellite">卫星地图</el-radio-button>
						</el-radio-group>

					</div>
					<My-Left-Page class="map_left" :isOpen="isOpen" :css="'show'" @openFunc='openFunc'
						:leftstyle="'yearactual'"></My-Left-Page>
					<div id="container" style=" width: 100%;z-index: 2;"> </div>
					<div class="map_right">
						<discharge></discharge>
					</div>
				</div>

			</div>

		</div>

	</div>

</template>




<script>
import Polygon from "ol/geom/Polygon"

import {
	getRegionHeatMap,
	getCity
} from '@/api/hzMJPT/mainInterface.js';
import areaData from './f.json'; // 导入同一目录下的 JSON 文件
import LinePage from "@/components/Myecharts/LinePage";
import ScreenFull from '@/components/Screenfull/index.vue';
import companyDialog from '@/components/companyDialog/companyDialog.vue';
import { Tile as TileLayer, Layer } from 'ol/layer'
import XYZ from "ol/source/XYZ";
import ImageStatic from 'ol/source/ImageStatic'

import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import LayerGroup from 'ol/layer/Group';
import { Style, Stroke, Fill, Circle as CircleStyle, Text } from 'ol/style'

import ImageLayer from 'ol/layer/Image';
import ImageWMS from 'ol/source/ImageWMS';
import { fromLonLat, transform, toLonLat } from "ol/proj";
import { Feature } from 'ol';
import { Vector as SourceVector } from 'ol/source'
import Point from 'ol/geom/Point';
import { Group, Vector as LayerVector } from 'ol/layer'

import MyLeftPage from "@/components/MyLeftPage/myleftPage"
import discharge from '@/components/MyRightPage/discharge'

import * as h337 from 'heatmap.js';

export default {
	components: {
		ScreenFull,
		companyDialog,
		LinePage,
		MyLeftPage,
		discharge
	},
	inject: ['reload'],
	data() {

		return {
			over: false,
			layers: [],
			layerShowType: 'baseDT',
			Name: ["NOX", "PM2.5", "VOCs", "SO₂"],
			isOpen: true,
			key: "d7a71c7ad105f0769725901b428c1a79",
			LinePageDate: {
				lpweek: [111],
				nox: [222],
				pm25: [333],
				vocs: [44],
				so2: [555],
			},
			ranks: [],

			textUnit: ["(吨)"],
			pfqd2: {
				title: "上一小时排放强度",
				list: [
					{
						name: "NOX",
						istop: false,
						num: "",
					},
					{
						name: "PM2.5",
						istop: false,
						num: "",
					},
					{
						name: "VOCs",
						istop: false,
						num: "",
					},
					{
						name: "SO₂",
						istop: true,
						num: "",
					},
				],
			},
			pfqd1: {
				title: "实时排放强度",
				list: [
					{
						name: "NOX",
						istop: true,
						num: "1",
					},
					{
						name: "PM2.5",
						istop: false,
						num: "2",
					},
					{
						name: "VOCs",
						istop: false,
						num: "3.1",
					},
					{
						name: "SO₂",
						istop: false,
						num: "2.3",
					},
				],
			},
			monthList: [
				{
					name: 'NOX',
					num: '12',
					datas: '',
				},
				{
					name: 'PM2.5',
					num: '10',
					datas: '',
				},
				{
					name: 'VOCs',
					num: '43',
					datas: '',
				},
				{
					name: 'SO₂',
					num: '11',
					datas: '',
				},
				{
					name: 'CO',
					num: '39',
					datas: '',
				},
				{
					name: '总碳',
					num: '70',
					datas: '',
				},
			],
			yearList: [
				{
					name: 'NOX',
					num: '121',
				},
				{
					name: 'PM2.5',
					num: '133',
				},
				{
					name: 'VOCs',
					num: '34',
				},
				{
					name: 'SO₂',
					num: '323',
				},
				{
					name: 'CO',
					num: '123',
				},
				{
					name: '总碳',
					num: '564',
				},
			]
		}
	},
	created() {
		//this.initWebSocket();
	},
	mounted() {

		const that = this

		const p1 = getCity().then((data) => {
			const promises = data.data.map((e) => {
				let city = {
					name: e.district,
					value: e.districtCode,
					label: e.district,
					districtCode: e.districtCode,
					geojson: JSON.parse(e.geoJson).coordinates,
					children: []
				};

				return city;

			});

			return Promise.all(promises).then((cities) => {
				that.enterprises = cities;
				return cities;
			});
		}).then(() => {


			// 更新热力图数据
			window.mapVue = this;

			// var bbox = [9526398.116099954, 5326564.904564987, 1.0193248464624465E7, 5698459.682702317];
			// var centerX = bbox[0]
			// var centerY = (bbox[1] + bbox[3]) / 2
			let mainCenter = fromLonLat([88.68855806979309, 44.30680640080587])
			var centerX = mainCenter[0]
			var centerY = mainCenter[1]

			var url = "http://172.16.0.202:8081/geoserver/base/wms?service=WMS&version=1.1.0&request=GetMap&layers=base%3Acj&bbox=9526398.116099954%2C5326564.904564987%2C1.0193248464624465E7%2C5698459.682702317&width=768&height=428&srs=EPSG%3A3857&styles=&format=image/png"
			var wmsLayer = new ImageLayer({
				source: new ImageWMS({
					url: url
				})
			});

			var layerGroup = new LayerGroup({
				layers: [wmsLayer]
			});

			const url_Vector = "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + this.key


			// function modifyTileColor(image) {
			// 	const canvas = document.createElement('canvas');
			// 	canvas.width = image.width;
			// 	canvas.height = image.height;
			// 	const ctx = canvas.getContext('2d');

			// 	// 绘制原始图像
			// 	ctx.drawImage(image, 0, 0);

			// 	// 设置合成操作，这里使用 'multiply' 模式，可根据需求调整
			// 	ctx.globalCompositeOperation = 'multiply';

			// 	// 设置蒙版颜色，这里使用你之前提到的科技感蓝色
			// 	ctx.fillStyle = 'rgb(70, 99, 153)';
			// 	ctx.fillRect(0, 0, canvas.width, canvas.height);

			// 	// 恢复默认合成操作
			// 	ctx.globalCompositeOperation = 'source-over';

			// 	return canvas;
			// }


			function modifyTileColor(image, options = {}) {
				// 创建主 Canvas 用于最终结果
				const canvas = document.createElement('canvas');
				canvas.width = image.width;
				canvas.height = image.height;
				const ctx = canvas.getContext('2d');

				// 创建背景层
				const backgroundCanvas = document.createElement('canvas');
				backgroundCanvas.width = image.width;
				backgroundCanvas.height = image.height;
				const bgCtx = backgroundCanvas.getContext('2d');

				// 配置选项
				const backgroundColor = options.backgroundColor || '#3E549C';

				// 1. 在背景 Canvas 上绘制背景色
				bgCtx.fillStyle = backgroundColor;
				bgCtx.fillRect(0, 0, backgroundCanvas.width, backgroundCanvas.height);

				// 2. 在主 Canvas 上绘制背景层
				ctx.drawImage(backgroundCanvas, 0, 0);

				// 3. 创建滤镜层 Canvas
				const filterCanvas = document.createElement('canvas');
				filterCanvas.width = image.width;
				filterCanvas.height = image.height;
				const filterCtx = filterCanvas.getContext('2d');

				// 4. 在滤镜层应用灰度和反色滤镜
				filterCtx.filter = 'grayscale(1) invert(1)';
				filterCtx.drawImage(image, 0, 0);

				// 5. 设置透明度并绘制到主 Canvas
				ctx.globalAlpha = 0.5;
				ctx.drawImage(filterCanvas, 0, 0);

				// 6. 重置上下文状态（可选）
				ctx.globalAlpha = 1;

				return canvas;
			}
			let layer_ = new TileLayer({
				source: new XYZ({
					url: url_Vector,
					wrapX: false,
					tileLoadFunction: function (tile, src) {
						const img = new Image();
						img.crossOrigin = 'anonymous';
						img.src = src;
						img.onload = function () {
							const modifiedCanvas = modifyTileColor(img);
							tile.getImage().src = modifiedCanvas.toDataURL();
						};
						img.onerror = function () {
							tile.setState(TileState.ERROR);
						};
					}
				}),

			})
			this.layers.push(layer_)

			var layers1 = new TileLayer({
				source: new XYZ({
					// url: "https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&x={x}&y={y}&z={z}&style=8",
					// url: "https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v10/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoieGlhb3NoaWhkIiwiYSI6ImNrNngzYnRhdzBqNm0zZnJ4eWZjdndrYzkifQ.qQjf8zANr9PsMpwq2NsRWQ",
					url: "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + this.key
					// attributions: '© 高德地图',
				}),

			})
			this.map = new Map({
				target: 'container',
				layers: [
					layer_],
				view: new View({
					center: [centerX, centerY],
					zoom: 7,
					minZoom: 7,
					maxZoom: 13
				})
			});
			that.initCompanyIcon();

			const today = new Date();
			// 将时、分、秒、毫秒设置为0
			today.setHours(0, 0, 0, 0);

			// 手动格式化日期
			const year = today.getFullYear();
			const month = String(today.getMonth() + 1).padStart(2, '0');
			const day = String(today.getDate()).padStart(2, '0');
			const hours = String(today.getHours()).padStart(2, '0');
			const minutes = String(today.getMinutes()).padStart(2, '0');
			const seconds = String(today.getSeconds()).padStart(2, '0');

			const stTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			getRegionHeatMap({ stTime: stTime }).then(data => {
				// 数据预处理：提取坐标点
				this.kri(data, layers1)

			});
		})

	},
	destroyed: function () { // 离开页面生命周期函数
		//this.websocketclose();
	},
	computed: {

	},
	methods: {
		initCompanyIcon() {
			const that = this
			let s = []
			let s1 = []

			that.enterprises.forEach(e => {
				const coordinates = e.geojson[0][0].map(([lng, lat]) => fromLonLat([lng, lat]));
				const polygonGeometry = new Polygon([coordinates]);

				const polygonFeature = new Feature({
					geometry: polygonGeometry
				});

				const polygonStyle = new Style({
					// stroke: new Stroke({
					// 	// color: '#74F4F9',
					// 	color: 'rgba(223,153,54)',
					// 	width: 2.2
					// }),
					// fill: new Fill({
					// 	color: 'rgba(0, 255, 255, 0.4)'
					// 	// color: 'rgba(247, 247, 247)'

					// })
					stroke: new Stroke({
						// color: 'rgb(7, 245, 197)',
						// width: 1
						width: 1,
						color: 'rgb(139, 229, 250)',

						lineDash: [5, 5]
					}),
					fill: new Fill({
						color: 'rgba(45, 158, 81,0.2)'
					}),
				});

				polygonFeature.setStyle(polygonStyle);

				const vectorSource = new SourceVector({
					features: [polygonFeature]
				});

				const vectorLayer = new LayerVector({
					source: vectorSource
				});

				that.map.addLayer(vectorLayer);



			})



		},
		changeLayerShowType() {

			if (this.map == undefined) {
				return
			}
			if (this.layers.length < 2) {
				const url_Vector = "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + this.key

				let layer = new TileLayer({
					source: new XYZ({
						url: url_Vector,
						wrapX: false,

					}),

				})
				this.layers.push(layer)
			}
			if (this.layerShowType != 'baseDT') {
				this.map.getLayers().setAt(0, this.layers[1]);
			}
			else {
				this.map.getLayers().setAt(0, this.layers[0]);
			}

		},
		kri(data, layers1) {
			let map = this.map

			this.total = data.total;

			// 1. 准备数据点
			const allPoints = data.data.map(e => {
				const [x, y] = fromLonLat([e.longitude, e.latitude]);
				return new Feature({
					geometry: new Point([x, y]),
					originalData: e,
					weight: e.countNum // 热力图权重
				});
			});

			const heatmapContainer = document.createElement("div")
			heatmapContainer.style.display = 'none';
			document.body.appendChild(heatmapContainer);

			// 初始化 heatMap.js
			const heatmapInstance = h337.create({
				container: heatmapContainer,
				radius: 1.5,
				maxOpacity: 1,
				minOpacity: 0,
				blur: 1,
				gradient: {
					'0.1': 'blue',
					'0.3': 'cyan',
					'0.5': 'lime',
					'0.7': 'yellow',
					'0.9': 'red'
				}
			});
			let heatmapLayer = null
			// 更新热力图容器尺寸和渲染器
			const mapSize = map.getSize();
			const viewExtent = map.getView().calculateExtent(mapSize);
			let canvas = null
			function updateHeatmap() {
				const mapSize = map.getSize();
				if (mapSize) {
					heatmapInstance._renderer.setDimensions(mapSize[0], mapSize[1]);

					// 转换为 heatMap.js 格式的数据
					const heatmapData = {
						max: 10,
						data: allPoints.map(point => {
							const coordinates = point.getGeometry().getCoordinates();
							const pixel = map.getPixelFromCoordinate(coordinates);

							let weight = 1;
							if (typeof point.get('weight') === 'number') {
								weight = point.get('weight');
							} else if (point.get('weight') && typeof point.get('weight').value === 'number') {
								weight = point.get('weight').value;
							}

							return {
								x: Math.round(pixel[0]),
								y: Math.round(pixel[1]),
								value: weight
							};
						})
					};

					// 更新热力图数据
					var zoom = map.getView().getZoom();
					var radius = Math.max(1, Math.min(60, zoom * 3)); // 半径范围限制在1-30之间

					// 更新热力图数据

					heatmapInstance.setData(heatmapData);

					// 更新热力图图层

					if (heatmapLayer) {
						canvas = heatmapInstance._renderer.canvas;

						const newImageSource = new ImageStatic({
							url: canvas.toDataURL(),
							imageExtent: viewExtent
						});
						// heatmapLayer.setSource(newImageSource);
					} else {
						canvas = heatmapInstance._renderer.canvas;
						const imageSource = new ImageStatic({
							url: canvas.toDataURL(),
							imageExtent: viewExtent
						});

						heatmapLayer = new ImageLayer({
							source: imageSource,
						});

						map.addLayer(heatmapLayer);
					}
				}
			}
			// 初始化时更新热力图
			updateHeatmap();
			map.addLayer(layers1)
			this.over = true
			// 监听地图移动和缩放事件
			// map.on('moveend', updateHeatmap);
			// map.on('zoomend', updateHeatmap);



		},
		openFunc() {
			/*左侧展开收起事件*/
			this.isOpen = !this.isOpen
		},


	},
}
</script>

<style>
/* 导航栏和标题的设置*/
.nav-menu {
	display: flex;
	align-items: center;
	/* 使导航项在垂直方向上居中 */
	/* 可以根据需要调整与其他元素的间距 */
}

.nav-item {
	text-decoration: none;
	color: #fff;
	display: inline-block;
	/* 导航项之间的水平间距 */
	padding: 5px 10px;
	/* 增加内边距，使导航项更美观且点击区域更大 */
	transition: all 0.2s ease;
	/* 添加过渡效果，使样式变化更平滑（可选） */
}

.nav-item:active,
.nav-item:hover,
.nav-item:focus {
	color: #fff;
	text-decoration: none;
	background-color: transparent;
	outline: none;
}

.active-nav {
	background-image: url("~@/assets/image/activate.png");
	background-repeat: no-repeat;
	background-size: contain;
	background-position: center;
	/* 添加这一行，使背景图在水平和垂直方向都居中 */

}

.el-dialog__body {
	padding: 0px 20px 20px 20px;
}

::-webkit-scrollbar {
	/*width: 0;宽度为0隐藏*/
	height: 6px;
	width: 3px;
}

::-webkit-scrollbar-thumb {
	border-radius: 2px;
	height: 50px;
	background-color: #00aaff;
}

::-webkit-scrollbar-track {
	box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
	border-radius: 0px;
	/*background-color: rgba(62, 106, 181, 0.8);*/
	background-color: rgba(0, 170, 255, 0.2);
}

.amap-logo {
	display: none;
	opacity: 0 !important;
}

.amap-copyright {
	opacity: 0;
}

.amap-marker-label {
	position: absolute;
	z-index: 2;
	border: 0px solid blue;
	background-color: rgba(31, 107, 134, 0.8);
	color: #ffaa00;
	white-space: nowrap;
	cursor: default;
	padding: 3px;
	font-size: 12px;
	line-height: 14px;
}
</style>
<style scoped>
.map_menu {
	position: absolute;
	z-index: 1;
	right: 32vw;
	bottom: 1vh;
	/*
		background-color: rgba(97, 118, 131, 1);
		*/
	border-radius: 5px;
	display: flex;
}

.bigScreenBodyDiv {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	background: no-repeat center top;
	background-size: cover;
	background-color: #172349;

}



.bigScreenBodyDivMain {
	flex: 1;
	width: 100%;
	display: flex;
}

.mappanel {
	background-color: rgba(27, 111, 250, 0);
	border: 0px solid rgba(27, 111, 250, 0.3) !important;
}

.outpanel {
	background-color: rgba(27, 111, 250, 0);
	border: 1px solid rgba(27, 111, 250, 0.3) !important;
	display: flex;
	flex-direction: column;
	margin-top: 10px;
}

.inpanel {
	display: flex;
	flex-direction: column;
	margin-top: 10px;
	background-color: rgba(27, 111, 250, 0);
}

.leftinpanel {
	border: 1px solid rgba(34, 170, 211, 0.8);
	border-image: -webkit-linear-gradient(top left, #00aaff 25%, rgba(27, 111, 250, 0.3) 50%, rgba(27, 111, 250, 0) 75%, rgba(27, 111, 250, 0) 95%) 10 10 10 10;
}

.rightinpanel {
	border: 1px solid rgba(34, 170, 211, 0.8);
	border-image: -webkit-linear-gradient(top right, #00aaff 25%, rgba(27, 111, 250, 0.3) 50%, rgba(27, 111, 250, 0) 75%, rgba(27, 111, 250, 0) 95%) 10 10 10 10;
}

.inpanel-title {
	width: 100%;
	height: 1.875rem;
	display: flex;
	padding-left: 1rem;
	background-color: rgba(27, 111, 250, 0);
	border: 0px solid rgba(27, 111, 250, 0.3) !important;
	border-bottom: 0px solid rgba(27, 111, 250, 0.5) !important;

}

.inpanel-title-left {
	width: 40%;
	height: 100%;
	text-align: left;
	line-height: 1.875rem;
	font-size: 0.875rem;
	color: #ffffff;
}

.inpanel-title-center {
	flex: 1;
	height: 100%;
	padding: 0.1875rem;
	line-height: 1.5rem;
	text-align: right;
}

.inpanel-title-right {
	width: 140px;
	height: 100%;
	/*
		line-height: 1.5rem;
		*/
	padding: 0rem 0.65rem;
	text-align: right;
	line-height: 1.875rem;
	font-size: 0.875rem;
	color: #ffffff;
}

.iconmore {
	color: #00B0FF;
	padding-right: 0.3125rem;
}

.el-checkbox__inner {
	background-color: rgba(0, 49, 72, 0.8);
	border: 1px solid rgba(0, 82, 120, 0.8);
}

.home_div {
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: 100%;
	display: flex;
}

#container {
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: calc(100% - 0px);
}

.map_alerm {
	position: absolute;
	z-index: 1;
	width: 30%;
	height: 150px;
	left: 35%;
	bottom: 10px;
	background-image: linear-gradient(to bottom, rgba(11, 58, 87, 0.8), rgba(11, 58, 87, 0.7), rgba(11, 58, 87, 0.7), rgba(11, 58, 87, 0.8), rgba(11, 58, 87, 0.8), rgba(11, 58, 87, 0.8), rgba(11, 58, 87, 0.9), rgba(11, 58, 87, 0.9), rgba(11, 58, 87, 0.9));
	border-radius: 5px;
	display: flex;
}


.enterprise-search-container {
	width: 300px;
	background-color: #1c2732;
	/* 深色背景色 */
	color: white;
	/* 白色字体 */
	border-radius: 5px;
	box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

.search-bar {
	display: flex;
	align-items: center;
	background-color: #283545;
	/* 搜索框背景色 */
	padding: 8px 12px;
	border-bottom: 1px solid #334155;
}

.search-bar input {
	width: 100%;
	background: transparent;
	border: none;
	color: white;
	outline: none;
}

.enterprise-list {
	list-style-type: none;
	padding: 0;
	margin: 0;
	max-height: 300px;
	/* 可根据需要调整最大高度 */
	overflow-y: auto;
	/* 出现内容过多时显示纵向滚动条 */
}

.enterprise-list li {
	padding: 8px 12px;
	cursor: pointer;
}

.enterprise-list li:hover {
	background-color: #283545;
	/* 鼠标悬停背景色 */
}

.blockTitle {
	width: 100%;
	height: 1.5vw;
	color: black;
	text-align: center;
	display: table;
	border-bottom: 1px solid rgba(34, 170, 211, 0.8);
	border-image: linear-gradient(to right, rgba(27, 111, 250, 0) 0%, rgba(27, 111, 250, 0.3) 25%, #00aaff 50%, rgba(27, 111, 250, 0.3) 75%, rgba(27, 111, 250, 0) 100%) 10 10 10 10;
}

.blockTitleText {
	width: 100%;
	height: 100%;
	display: table-cell;
	vertical-align: middle;
	font-size: 0.8vw;
}
</style>
<style>
.el-tree-node__expand-icon.expanded {
	-webkit-transform: rotate(0deg);
	transform: rotate(0deg);
}


.el-tree-node__content {

	margin-bottom: 10px;

}

.el-tree-node__content:hover {
	background-color: transparent;
}

.el-tree-node:focus>.el-tree-node__content {
	background-color: #1E374F;
}

.tree-container {
	height: 240px;
	/* 设置容器高度 */
	overflow-y: auto;
	/* 当内容超出高度时显示垂直滚动条 */
}

.tree-container::-webkit-scrollbar {
	width: 10px;
	background: none;
	border-radius: 5px;

}

.tree-container::-webkit-scrollbar-thumb {
	background: rgb(37, 114, 135);
	/* 设置滚动条滑块颜色为蓝色 */
	border-radius: 5px;
}

.el-input__inner {
	color: white;
	background: rgba(3, 89, 115, 0.8);
}

input::-webkit-input-placeholder {

	-webkit-text-fill-color: white;

}
</style>
<style scoped lang="scss">
.map_left {
	height: 100%;
	z-index: 3;
	background-color: white;
	background: rgba(0, 0, 0, .6) url("~@/assets/image/actual-left.png") no-repeat 50%;

}

.map_right {
	background: url('~@/assets/image/main-bg.png') no-repeat center;
	z-index: 3;
	// background-color: #172349;

}
</style>